import socket
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ

selector = DefaultSelector()


class Fetcher:

    def __init__(self, host):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.setblocking(False)
        self.host = 'www.baidu.com'
        self.data = b""

    def get_url(self):
        try:
            self.client.connect((self.host, 80))
        except BlockingIOError as e:
            # 做一些其他的事情
            pass
        selector.register(self.client.fileno(), EVENT_WRITE, self.connected)

    def connected(self, key):
        """
        :param key: 文件描述符
        :return:
        """
        selector.unregister(key.fd)
        send_txt = "GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n"
        self.client.send(send_txt.format("/", self.host).encode("utf8"))

        selector.register(self.client.fileno(), EVENT_READ, self.readadle)

    def readadle(self, key):
        d = self.client.recv(1024)
        if d:
            self.data += d
        else:
            selector.unregister(key.fd)
            data = self.data.decode("utf8")
            print(data)


def loop_forever():
    # 事件循环
    while 1:
        ready = selector.select()
        for key, mask in ready:
            # 当获取到描述符的时候调用对应的方法
            call_back = key.data
            call_back(key)


if __name__ == '__main__':
    fetcher = Fetcher("www.baidu.com")
    fetcher.get_url()
    loop_forever()
